package com.health.gateway.filter;



import com.health.common.utils.JwtUtils;
import com.health.gateway.config.AuthProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

import static com.health.common.constant.UserConstant.AUTH_HEADER;
import static com.health.common.constant.UserConstant.USER_INFO;


/**
 * @author zhexueqi
 * @ClassName AuthGlobalFilter
 * @since 2024/5/13    15:21
 */
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获得请求
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否需要做登录拦截
        if (isExclude(request.getPath().toString())){
            //放行
            return chain.filter(exchange);
        }
        //3.获取token
        String token = null;
        List<String> authorizations = request.getHeaders().get(AUTH_HEADER);
        if (authorizations != null && !authorizations.isEmpty()){
            token = authorizations.get(0);
        }
        //4.校验并解析token
        String userKey = null;
        try {
            userKey = JwtUtils.getUserKey(token);
        } catch (Exception e) {
            //拦截，设置相应状态码为401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 5. 传递用户信息
        String userInfo = String.valueOf(userKey);
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header(USER_INFO, userInfo))
                .build();

        // 6.放行
        return chain.filter(swe);
    }

    private boolean isExclude(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
